package models

import (
	"gorm.io/gorm"
)

type Warehouse struct {
	gorm.Model
	Orders string  `gorm:"type:varchar(100)"`
	Types  string  `gorm:"type:varchar(30)"`
	Name   string  `gorm:"type:varchar(50)"`
	Data   string  `gorm:"type:datetime"`
	Num    int     `gorm:"type:int(3)"`
	Price  float64 `gorm:"type:decimal(10,2)"`
	People string  `gorm:"type:varchar(20)"`
}

func (w *Warehouse) List(keyword string, page, pageSize int) (list []Warehouse, err error) {

	query := DB.Debug()

	if keyword != "" {
		query = query.Where("people like ?", "%"+keyword+"%")
	}

	err = query.Scopes(Paginate(page, pageSize)).Order("num asc").Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
